<template>
  <!-- 添加考试 -->
  <el-drawer
    title
    :visible.sync="examDialogVisible"
    direction="btt"
    append-to-body
    size="100%"
    custom-class="drawer-box"
    :before-close="handleClose"
  >
    <el-container style="min-height: 100%">
      <el-header height="auto">
        <div style="margin-top: 20px">
          <el-form ref="form" :model="form" :rules="rules" :inline="true">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" :disabled="!!form.courseStatus"/>
            </el-form-item>
            <el-form-item label="时长（分钟）" prop="duration">
              <el-input-number
                controls-position="right"
                type="number"
                v-model="form.duration"
                :min="1"
                :disabled="!!form.courseStatus"
              />
            </el-form-item>
            <el-form-item label="达标分数" prop="passMark">
              <el-input-number
                controls-position="right"
                v-model="form.passMark"
                :min="1"
                :disabled="!!form.courseStatus"
              />
            </el-form-item>
            <el-form-item label="试题乱序" prop="quesDisorder">
              <el-radio-group v-model="form.quesDisorder" :disabled="!!form.courseStatus">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <!--            <el-col :span="3">-->
            <!--              <el-form-item label="允许考试次数" prop="number">-->
            <!--                <template>-->
            <!--                  <el-popover-->
            <!--                    placement="top"-->
            <!--                    width="100"-->
            <!--                    trigger="hover"-->
            <!--                    content="注:0为无限次数.">-->
            <!--                    <el-input-number slot="reference" v-model="form.number" controls-position="right" :min="0" :max="100"></el-input-number>-->
            <!--                  </el-popover>-->
            <!--                </template>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-form-item label="考试次数" prop="number">
              <el-radio-group
                v-model="number_type"
                @change="numberTypeChange"
                :disabled="!!form.courseStatus"
              >
                <el-radio-button :label="0">无限</el-radio-button>
                <el-radio-button :label="1">一次</el-radio-button>
                <el-radio-button :label="2">多次</el-radio-button>
              </el-radio-group>
              <el-input-number
                v-if="parseInt(number_type) === 2"
                v-model="form.number"
                :min="2"
                :max="99999"
                :disabled="!!form.status"
                controls-position="right"
                :precision="0"
              />
              <p
                v-if="parseInt(number_type) === 2"
                style="font-size: 12px; color: #999"
              >(大于2次时，只能进行一次考试，其余次数为补考次数;最大次数为99999)</p>
            </el-form-item>
            <el-form-item style="margin-left: 200px">
              <el-button
                v-if="this.form.courseStatus !=1"
                class="el-icon-check"
                type="text"
                @click="onSubmit"
                :loading="loading"
                style="color: #67C23A;font-size:24px"
              />
              <el-button
                class="el-icon-close"
                type="text"
                @click="handleClose"
                style="color: #F56C6C;font-size: 24px"
              />
            </el-form-item>
            <!--            <el-col :span="4">-->
            <!--                <el-form-item label="是否及格才算完成">-->
            <!--                    <el-radio-group v-model="form.resource" style="width: 100%">-->
            <!--                        <el-radio label="1">是</el-radio>-->
            <!--                        <el-radio label="0">否</el-radio>-->
            <!--                    </el-radio-group>-->
            <!--                </el-form-item>-->
            <!--            </el-col>-->
          </el-form>
        </div>
        <hr/>
        <el-dialog
          title="分类管理"
          :visible.sync="dialogFormVisible"
          :close-on-click-modal="false"
          :show-close="false"
          :close-on-press-escape="false"
          append-to-body
          width="30%"
        >
          <learn-cate ref="learnCate" v-if="learnCate" :setCurrent="setCurrent" :current="current"/>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
          </div>
        </el-dialog>
      </el-header>
      <el-main>
        <el-button type="primary" round style="margin-bottom: 10px" @click="openSelectTopic(1)">选题组卷</el-button>
        <!-- <el-button type="primary" round >选择试卷</el-button>-->
        <table border="0" cellpadding="10" cellspacing="0" width="100%" class="add-exam-table">
          <tr align="left">
            <th>类型</th>
            <th>单选</th>
            <th>多选</th>
            <th>判断</th>
            <!--
                        <th>排序</th>
            <th>填空</th>-->
            <th>共计</th>
          </tr>
          <tr>
            <th align="left">数量</th>
            <td class="add-exam-table-bg">{{oddTotalTopic}}</td>
            <td class="add-exam-table-bg">{{manyTotalTopic}}</td>
            <td class="add-exam-table-bg">{{judgeTotalTopic}}</td>
            <!--
                        <td class="add-exam-table-bg">&#45;&#45;</td>
            <td class="add-exam-table-bg">&#45;&#45;</td>-->
            <td class="add-exam-table-bg">{{oddTotalTopic + manyTotalTopic + judgeTotalTopic}}</td>
          </tr>
          <tr>
            <th align="left">分数</th>
            <td class="add-exam-table-bg">{{oddTotalScore}}</td>
            <td class="add-exam-table-bg">{{manyTotalScore}}</td>
            <td class="add-exam-table-bg">{{judgeTotalScore}}</td>
            <!--
                        <td class="add-exam-table-bg">&#45;&#45;</td>
            <td class="add-exam-table-bg">&#45;&#45;</td>-->
            <td class="add-exam-table-bg">{{oddTotalScore + judgeTotalScore + manyTotalScore}}</td>
          </tr>
        </table>
        <!-- 选择试题 -->
        <selectTopic
          ref="selectTopic"
          v-show="isSelectTopic"
          :examData="examData"
          :setExamData="setExamData"
        />
        <!--        <topic ref="topic" v-show="isTopic" :topic="topic" :setTopic="setTopic"/>-->
        <div class="add-exam-box">
          <div class="add-exam-fraction">
            <ul>
              <li v-for="(val,key) in examData" :key="key" @click="goAnchor(`#mao_${key}`)" v-show="val.length">
                <h3>
                  <template v-if="parseInt(key) === 1">单选题</template>
                  <template v-else-if="parseInt(key) === 2">多选题</template>
                  <template v-else>判断题</template>
                </h3>
                <el-form :inline="true">
                  <el-form-item label="每题分数:">
                    <template v-if="parseInt(key) === 1">
                      <el-input-number
                        type="number"
                        v-model="oddFraction"
                        :precision="0"
                        @change="changeFraction($event,key)"
                        :disabled="!!form.courseStatus"
                      />
                    </template>
                    <template v-else-if="parseInt(key) === 2">
                      <el-input-number
                        type="number"
                        v-model="manyFraction"
                        :precision="0"
                        @change="changeFraction($event,key)"
                        :disabled="!!form.courseStatus"
                      />
                    </template>
                    <template v-else>
                      <el-input-number
                        type="number"
                        v-model="judgeFraction"
                        :precision="0"
                        @change="changeFraction($event,key)"
                        :disabled="!!form.courseStatus"
                      />
                    </template>
                  </el-form-item>
                </el-form>
              </li>
            </ul>
          </div>
          <div class="add-exam-list-box">
            <ul :id="`mao_${key}`" class="add-exam-list" v-for="(val,key) in examData" :key="key" v-show="val.length">
              <li v-for="(x,i) in val" :key="i">
                <h3>
                  <span v-if="parseInt(key) === 1">单选题</span>
                  <span v-else-if="parseInt(key) === 2">多选题</span>
                  <span v-else>判断题</span>
                  <div>
                    <p>
                      题目分数：
                      <input
                        type="number"
                        @change="scoreChange($event,key,i)"
                        v-model="x.score"
                        :disabled="!!form.courseStatus"
                      />
                    </p>
                  </div>
                </h3>
                <h6>{{x.info}}</h6>
                <ul>
                  <li v-for="(i, index) in x.questionOptionEntities" :key="index">{{i.key}}. {{i.option}}</li>
                </ul>
                <p>标准答案: {{x.answ}}</p>
                <div class="add-exam-list-analysis" v-if="x.analysis">
                  <p>试题解析:</p>
                  <p>{{x.analysis}}</p>
                </div>
                <div class="add-exam-list-difficult">
                  <div>
                    <span>难易度：</span>
                    <template v-if="parseInt(x.level) === 0">简单</template>
                    <template v-else-if="parseInt(x.level) === 1">一般</template>
                    <template v-else>困难</template>
                  </div>
                  <div>
                    <!--                    向上-->
                    <el-button
                      :disabled="!!form.courseStatus"
                      type="info"
                      class="el-icon-top"
                      @click="_up(val,i)"
                      circle
                    />
                    <!--                    向下-->
                    <el-button
                      :disabled="!!form.courseStatus"
                      type="info"
                      class="el-icon-bottom"
                      @click="_down(val,i)"
                      circle
                    />
                    <el-button
                      :disabled="!!form.courseStatus"
                      type="danger"
                      icon="el-icon-delete"
                      @click="_delect(val,i,key)"
                      circle
                    />
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </el-main>
      <!--      <el-footer>-->
      <!--        <hr>-->
      <!--        <div class="learn-drawer-range-box-buttons">-->
      <!--          <el-button type="info" round @click="handleClose">取消</el-button>-->
      <!--          <el-button round type="primary" @click="onSubmit">立即创建</el-button>-->
      <!--        </div>-->
      <!--      </el-footer>-->
    </el-container>
  </el-drawer>
</template>

<script>
  import {goAnchor} from './../../utils'
  import selectTopic from './selectTopic'
  import topic from './topic'
  import learnCate from './../../views/modules/learn/learncate'

  export default {
    name: 'addOperation',
    props: ['setaddOperation'],
    components: {selectTopic, learnCate, topic},
    data() {
      return {
        topic: {},
        topicArr: [],
        quesType: 0,
        dialogFormVisible: false,
        isSelectTopic: false,
        isTopic: false,
        loading: false,
        isRandomTopic: false,
        paperId: null,
        current: {},
        learnCate: false,
        oddTotalScore: 0,
        manyTotalScore: 0,
        judgeTotalScore: 0,
        oddTotalTopic: 0,
        manyTotalTopic: 0,
        judgeTotalTopic: 0,
        oddFraction: null,
        manyFraction: null,
        judgeFraction: null,
        formLabelWidth: '120px',
        examDialogVisible: false,
        form: {
          id: '',
          name: '',
          cateId: '',
          courseStatus: '',
          state: false,
          duration: '',
          number: -1,
          passMark: '',
          quesDisorder: 1,
          optionDisorder: 0
        },
        index: 0,
        number_type: 0,
        rules: {
          name: [{required: true, message: '请输入考试名称', trigger: 'blur'}],
          duration: [
            {required: true, message: '考试时长不能为空', trigger: 'blur'}
          ],
          passMark: [
            {required: true, message: '达标分数不能为空', trigger: 'blur'}
          ],
          // number: [{required: true, message: '考试次数不能为空', trigger: 'blur'}],
          quesDisorder: [
            {required: true, message: '试题是否乱序', trigger: 'blur'}
          ]
        },
        examData: {} /* 选择的题的数据 */,
        examTotal: [] /* 统一选择的题的总数 */
      }
    },
    methods: {
      init(id, index) {
        this.index = index
        this.loading = false
        this.oddTotalScore = 0
        this.manyTotalScore = 0
        this.judgeTotalScore = 0
        this.oddTotalTopic = 0
        this.manyTotalTopic = 0
        this.judgeTotalTopic = 0
        this.form = {
          id: '',
          courseStatus: '',
          name: '',
          cateId: '',
          duration: '',
          number: '',
          passMark: '',
          optionDisorder: 0,
          quesDisorder: 1
        }
        this.form.id = id || ''
        if (this.form.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/train-admin/course/getcourseexaminfo/${this.form.id}`
            ),
            method: 'post'
          }).then(res => {
            this.form.courseStatus = res.data.courseStatus
            this.form.duration = res.data.duration / 60
            this.form.name = res.data.name
            this.form.passMark = res.data.passMark
            this.form.number_type = res.data.number
            this.form.quesDisorder = res.data.quesDisorder
            this.examData = {
              '1': res.data.singerChoiceqstEntities,
              '2': res.data.multiChoiceqstEntities,
              '3': res.data.judgeqstEntities
            }
            this._switch()
          })
        } else {
          this.examData = {}
        }
        this.examDialogVisible = true
      },
      // 分类管理
      setCurrent(data) {
        if (data.id) {
          this.current = data
          this.form.cateId = data.id
          this.$nextTick(_ => this.$refs['form'].validateField('cateId'))
        }
      },
      // 单 多 判断
      goAnchor,
      _switch(key) {
        if (key) {
          switch (parseInt(key)) {
            case 1:
              // eslint-disable-next-line no-eval
              this.oddTotalScore = this.examData[key].length ? eval(this.examData[key].map(x => x.score).join('+')) : 0
              this.oddTotalTopic = this.examData[key].length || 0
              let isOddTrue
              this.examData[key].forEach((x, i, arr) => {
                isOddTrue = arr[0].score
                if (x.score !== arr[0].score) {
                  isOddTrue = null
                  return false
                }
              })
              if (isOddTrue) {
                this.oddFraction = isOddTrue
              } else {
                this.oddFraction = null
              }
              break
            case 2:
              // eslint-disable-next-line no-eval
              this.manyTotalScore = this.examData[key].length ? eval(this.examData[key].map(x => x.score).join('+')) : 0
              this.manyTotalTopic = this.examData[key].length || 0
              let isManyTrue
              this.examData[key].forEach((x, i, arr) => {
                isManyTrue = arr[0].score
                if (x.score !== arr[0].score) {
                  isManyTrue = null
                  return false
                }
              })
              if (isManyTrue) {
                this.manyFraction = isManyTrue
              } else {
                this.manyFraction = null
              }
              break
            default:
              // eslint-disable-next-line no-eval
              this.judgeTotalScore = this.examData[key].length ? eval(this.examData[key].map(x => x.score).join('+')) : 0
              this.judgeTotalTopic = this.examData[key].length || 0
              let isJudgeTrue
              this.examData[key].forEach((x, i, arr) => {
                isJudgeTrue = arr[0].score
                if (x.score !== arr[0].score) {
                  isJudgeTrue = null
                  return false
                }
              })
              if (isJudgeTrue) {
                this.judgeFraction = isJudgeTrue
              } else {
                this.judgeFraction = null
              }
              break
          }
        } else {
          if (Object.keys(this.examData).length) {
            for (let key in this.examData) {
              this._switch(key)
            }
          }
        }
      },
      // 每题分数
      changeFraction(val, key) {
        this.examData[key].forEach(x => {
          x.score = val || 1
        })
        // sessionStorage.setItem('examData', JSON.stringify(this.examData))
        this._switch(key)
      },
      // 题目分数
      scoreChange(e, key, i) {
        this.examData[key][i].score = e.target.value || 1
        this._switch(key)
        switch (parseInt(key)) {
          case 1:
            this.oddFraction = null
            break
          case 2:
            this.manyFraction = null
            break
          default:
            this.judgeFraction = null
            break
        }
        // sessionStorage.setItem('examData', JSON.stringify(this.examData))
      },
      handleClose() {
        this.examDialogVisible = false
      },
      // 选题组件
      openSelectTopic(course) {
        this.isTopic = false
        this.topicArr = []
        this.isSelectTopic = true
        // this.examData = JSON.parse(sessionStorage.getItem('examData') || '{}')
        // this.examData = {}
        this._switch()
        this.$nextTick(_ => {
          this.$refs.selectTopic.init(this.examData, course)
        })
      },
      numberTypeChange(val) {
        this.form.number =
          parseInt(val) === 0 ? -1 : parseInt(val) === 1 ? 1 : this.form.number
        this.$nextTick(_ => this.$refs['form'].validateField('number'))
      },
      onSubmit() {
        this.loading = true
        if (
          this.form.passMark >
          this.oddTotalScore + this.judgeTotalScore + this.manyTotalScore
        ) {
          this.$notify.error({
            title: '错误',
            message: '达标分数大于试卷总分'
          })
          this.loading = false
          return
        }
        // eslint-disable-next-line eqeqeq
        if (this.form.name == '') {
          this.$notify.error({
            title: '错误',
            message: '试卷名称不能为空'
          })
          this.loading = false
          return
        }
        let data = []
        this.$refs['form'].validate(valid => {
          if (valid) {
            for (let key in this.examData) {
              data = data.concat(this.examData[key])
            }
            data = data.map(x => ({
              id: x.id,
              score: x.score,
              quesType: x.quesType
            }))
            // if (this.compType === 1 || this.compType === 2) {
            //   if (!this.topicArr.length) {
            //     return this.$notify.error({
            //       title: '错误',
            //       message: '试题为空，不能添加考试'
            //     })
            //   }
            //
            //   data = this.topicArr
            //   data = data.map(x => {
            //     delete x['totalTopic']
            //     return x
            //   })
            // }
            let _data = {
              id: this.form.id,
              name: this.form.name,
              duration: this.form.duration * 60,
              passMark: this.form.passMark,
              optionDisorder: this.form.optionDisorder,
              quesDisorder: this.form.quesDisorder,
              quesInfo: JSON.stringify(data),
              delDefault: 0,
              number: this.form.number || -1,
              totalQuesCount: `${this.oddTotalTopic +
              this.manyTotalTopic +
              this.judgeTotalTopic}`,
              totalScore: `${this.oddTotalScore +
              this.judgeTotalScore +
              this.manyTotalScore}`
            }
            // if (this.paperId) _data = Object.assign(_data, {'id': this.paperId})
            this.$http({
              url: this.$http.adornUrl(
                `/train-admin/course/${
                  !this.form.id ? 'addcourseexam' : 'updatecourseexam'
                }`
              ),
              method: 'post',
              data: _data
            }).then(res => {
              if (res && parseInt(res.code) === 200) {
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success'
                })
                this.examData = {}
                this.setaddOperation(res.data, this.index)
                this.examDialogVisible = false
              } else {
                this.$message.warning(res.msg)
              }
              this.loading = false
            })
            //   .catch(_ => {
            //   this.loading = false
            // })
          }
        })
      },
      setExamData(data) {
        this.examData = data
        // sessionStorage.setItem('examData', JSON.stringify(data))
        this._switch()
        this.$forceUpdate()
      },
      // 两个元素交换位置
      swapArray(arr, index1, index2) {
        arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      },
      _up(arr, i) {
        if (parseInt(i) !== 0) {
          this.swapArray(arr, i - 1, i)
          this.$forceUpdate()
          // sessionStorage.setItem('examData', JSON.stringify(this.examData))
        } else {
          this.$message.warning('已经处于置顶，无法上移')
        }
      },
      _down(arr, i) {
        if (parseInt(i) !== arr.length - 1) {
          this.swapArray(arr, i, i + 1)
          this.$forceUpdate()
          // sessionStorage.setItem('examData', JSON.stringify(this.examData))
        } else {
          this.$message.warning('已经处于置底，无法下移')
        }
      },
      _delect(arr, i, key) {
        arr.splice(i, 1)
        // sessionStorage.setItem('examData', JSON.stringify(this.examData))
        this._switch(key)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .add-exam-box {
    padding-top: 10px;
    display: flex;
    justify-content: space-between;

    .add-exam-fraction {
      padding: 10px 50px 10px 0;
      width: 300px;

      ul {
        margin: 0;
        padding: 0;
        list-style-type: none;

        li {
          margin-bottom: 50px;
          padding: 10px 20px;
          border-radius: 5px;
          box-shadow: 2px 2px 5px #333333;
          cursor: pointer;
        }
      }
    }

    .add-exam-list-box {
      flex: 1;
      height: 560px;
      overflow: auto;
      border: 1px dashed #999;
    }
  }

  .add-exam-table {
    font-size: 12px;
    font-weight: 300;

    th {
      font-weight: 300;
      background: #e9eef1;
      border: 1px solid #eee;
    }

    td {
      border-width: 0 1px 1px;
      border-color: #eee;
      border-style: solid;
    }
  }

  .add-exam-list {
    &:first-of-type {
      margin: 0;
    }

    margin: 10px 0 0;
    list-style-type: none;
    padding: 20px;
    background: #e9e9eb;

    li {
      margin: 10px;
      padding: 20px 30px;
      background: white;
      font-size: 12px;
      color: #72767b;

      h3,
      h6 {
        margin: 0;
      }

      h3 {
        color: #333;
        padding: 10px 0;
        font-size: 16px;
        display: flex;
        justify-content: space-between;

        p {
          font-weight: 400;
          margin: 0;
        }
      }

      h6 {
        padding-left: 5px;
        font-size: 14px;
        font-weight: 400;
      }

      ul {
        padding: 10px;
        list-style: none;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        li {
          margin: 0;
          padding: 5px 10px;
          width: 50%;
        }
      }

      .add-exam-list-analysis {
        display: flex;
        padding: 10px 0;

        p {
          margin: 0;
        }

        p:last-of-type {
          flex: 1;
          height: 40px;
          border: 1px solid #72767b;
          margin: 0 5px 0 30px;
          padding: 5px;
        }
      }

      .add-exam-list-difficult {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;

        div:first-of-type {
          display: flex;
          align-items: center;

          p {
            margin: 0 10px;
            padding: 10px;
            border: 1px solid #72767b;
          }
        }
      }
    }
  }
</style>
